<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>商品详情</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        .navbar {
            background-color: #ff5000;
            color: white;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .navbar .logo {
            display: flex;
            align-items: center;
        }
        .navbar .logo span {
            margin-left: 10px;
        }
        .navbar a {
            color: white;
            text-decoration: none;
            margin: 0 10px;
        }
        .navbar button {
            background-color: white;
            color: #ff5000;
            border: none;
            padding: 5px 10px;
            margin-left: 10px;
            border-radius: 5px;
            cursor: pointer;
        }
        .product-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            display: flex;
            justify-content: space-between;
        }
        .product-image {
            flex: 1;
            margin-right: 20px;
        }
        .product-image img {
            max-width: 100%;
            height: 300px;
            border-radius: 5px;
        }
        .product-details {
            flex: 2;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f5f5f5;
        }
        .product-details h2 {
            font-size: 24px;
            margin-bottom: 10px;
        }
        .product-details p {
            font-size: 16px;
            line-height: 1.6;
            margin: 10px 0;
        }
        .product-details .price {
            color: #ff5000;
            font-size: 20px;
            margin: 10px 0;
        }
        .product-details .product-quantity {
            margin-bottom: 10px;
        }
        .product-details .product-quantity label {
            margin-right: 5px;
        }
        .product-details .product-quantity input {
            width: 50px;
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
        .product-buttons {
            margin-top: 20px;
        }
        .product-buttons button {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-right: 10px;
        }
        .add-to-cart {
            background-color: #ff5000;
            color: white;
        }
        .buy-now {
            background-color: #00c800;
            color: white;
        }
        .gallery-container {
            margin-top: 20px;
            overflow-x: auto;
            border: 1px solid #ccc;
            padding: 10px;
            white-space: nowrap;
        }
        .gallery-container .imageWrapper {
            display: inline-block;
            margin-right: 10px;
            vertical-align: top;
        }
        .gallery-container .imageWrapper img {
            height: 150px;
            object-fit: cover;
            cursor: pointer;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div class="navbar">
    <div class="logo">机械工业</div>
    <div class="nav-links">
        <a id="index1Link" href="#">首页</a>
        <a id="userMessageLink" href="#">我的</a>
        <a id="cartLink" href="#">购物车</a>
    </div>
</div>

<div class="product-container" id="productContainer">
    <!-- 商品信息将通过 JavaScript 动态生成 -->
</div>

<script>
    // 获取 URL 中的商品 ID
    function getUserIdFromUrl() {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('userId');
    }

    const userId = getUserIdFromUrl();
    const userMessageLink = document.getElementById("userMessageLink");
    const index1Link = document.getElementById("index1Link");
    const cartLink = document.getElementById("cartLink");

    userMessageLink.href = `userMessage?id=${userId}`;
    index1Link.href = `index1?id=${userId}`;
    cartLink.href = `cart?id=${userId}`;


    var urlParams = new URLSearchParams(window.location.search);
    var productId = urlParams.get('id');


    // 获取商品信息并展示
    function loadProductDetails() {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/products/' + productId, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                var product = JSON.parse(xhr.responseText);
                var productContainer = document.getElementById('productContainer');

                // 动态生成商品信息的 HTML
                var html = `
                    <div class="product-image">
                        <img src="${product.iconUrl}" alt="${product.name}">
                        <div class="gallery-container" id="galleryContainer"></div>
                    </div>
                    <div class="product-details">
                        <h2>${product.name}</h2>
                        <p class="price">￥${product.price}</p>
                        <p><strong>库存：</strong>${product.stock}</p>
                        <p>${product.detail}</p>
                        <div class="product-quantity">
                            <label for="quantity">数量：</label>
                            <input type="number" id="quantity" value="1" min="1">
                        </div>
                        <div class="product-buttons">
                            <button class="add-to-cart" onclick="addToCart(${product.id})">加入购物车</button>
                            <button class="buy-now" onclick="buyNow(${product.id})">立即购买</button>
                        </div>
                    </div>
                `;
                productContainer.innerHTML = html;

                // 显示组图
                displayGallery(product.subImages);
            }
        };
        xhr.send();
    }

    // 添加到购物车的函数
    function addToCart(productId) {
        var quantity = document.getElementById('quantity').value; // 获取商品数量

        // 发送 AJAX 请求
        $.ajax({
            type: "POST",
            url: "/trolleys/add",
            contentType: "application/json",
            data: JSON.stringify({
                userId: userId,
                productId: productId,
                quantity: parseInt(quantity) // 将数量转换为整数
            }),
            success: function(response) {
                alert("成功将商品加入购物车，商品ID：" + productId);
                // 可以在成功后做一些界面上的变化或其他操作
            },
            error: function() {
                alert("添加商品到购物车失败，请重试！");
            }
        });
    }

    // 立即购买的函数
    function buyNow(productId) {
        var quantity = document.getElementById('quantity').value; // 获取商品数量
        // 跳转到订单确认页面
        window.location.href = `orderconfirmation?productId=${productId}&quantity=${quantity}&userId=${userId}`;
    }

    // 显示组图的函数
    function displayGallery(subImages) {
        var galleryContainer = document.getElementById('galleryContainer');
        if (subImages) {
            var subImagesArray = subImages.split(',');
            subImagesArray.forEach(url => {
                var imageWrapper = document.createElement('div');
                imageWrapper.className = 'imageWrapper';
                var img = document.createElement('img');
                img.src = url.trim();
                imageWrapper.appendChild(img);
                galleryContainer.appendChild(imageWrapper);
            });
        }
    }

    // 页面加载完成时调用加载商品信息的函数
    window.onload = loadProductDetails;
</script>
</body>
</html>
